package com.sgcc.sx.pmos.e_sx_mall.activity;

import android.graphics.Color;
import android.graphics.Paint;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.ClipboardUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.sgcc.sx.pmos.arouter.mall.MallArouterPath;
import com.sgcc.sx.pmos.common.base.BaseRecyclerAdapter;
import com.sgcc.sx.pmos.common.base.MvpBaseActivity;
import com.sgcc.sx.pmos.common.bean.BaseResponse;
import com.sgcc.sx.pmos.common.bean.EventCenter;
import com.sgcc.sx.pmos.common.bean.PackageBean;
import com.sgcc.sx.pmos.common.bean.StoreInfoBean;
import com.sgcc.sx.pmos.common.dialog.PackageDetailsPopView;
import com.sgcc.sx.pmos.common.dialog.PriceTipickPopView;
import com.sgcc.sx.pmos.common.dialog.StockPopView;
import com.sgcc.sx.pmos.common.http.HttpInterConst;
import com.sgcc.sx.pmos.common.utils.ArguConstant;
import com.sgcc.sx.pmos.common.utils.BigDecimalUtils;
import com.sgcc.sx.pmos.common.utils.DateUtils;
import com.sgcc.sx.pmos.common.utils.DialogUtil;
import com.sgcc.sx.pmos.common.utils.EnumUtils;
import com.sgcc.sx.pmos.common.utils.PackageContrastUtils;
import com.sgcc.sx.pmos.common.utils.TextUtil;
import com.sgcc.sx.pmos.common.utils.UserManager;
import com.sgcc.sx.pmos.common.widget.CustomScrollView;
import com.sgcc.ln.pmos.common.widget.TitleBar;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.sx.pmos.e_sx_mall.adapter.MonthAdapter;
import com.sgcc.sx.pmos.e_sx_mall.bean.FloMainSchemeBean;
import com.sgcc.sx.pmos.e_sx_mall.bean.MallGoodsBean;
import com.sgcc.sx.pmos.e_sx_mall.bean.PackageDetailsBean;
import com.sgcc.sx.pmos.e_sx_mall.bean.PackageInfoBean;
import com.sgcc.sx.pmos.e_sx_mall.bean.PriceAndPriceDetailBean;
import com.sgcc.sx.pmos.e_sx_mall.bean.PublicDifContentBean;
import com.sgcc.sx.pmos.e_sx_mall.bean.SchemeCombBySchemeIdYHBean;
import com.sgcc.sx.pmos.e_sx_mall.contract.PackageDetailsContract;
import com.sgcc.sx.pmos.e_sx_mall.presenter.PackageDetailsPresenter;

import org.greenrobot.eventbus.EventBus;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

/**
 * 套餐详情
 * <p>
 * android锚点定位 Android 实现锚点定位思路详解
 * http://www.qb5200.com/article/353138.html
 */
@Route(path = MallArouterPath.MALL_PACKAGEDETAILS)
public class PackageDetailsActivity extends MvpBaseActivity<PackageDetailsPresenter> implements PackageDetailsContract.View {

    private TitleBar mTitleBar;
    private TabLayout mTablayout;
    private CustomScrollView mScrollView;
    private LinearLayout mContainer;
    private ImageView mIvAddPkNew;
    private ImageView mIvGoPk;
    private LinearLayout mLlStore;
    private LinearLayout mLlCollection;
    private RecyclerView mRlContent;
    private ImageView mIvCollection;
    private TextView mTvCollection;
    private RelativeLayout placeOrderNow;//立即下单按钮
    private RelativeLayout placeOrderBargain;//议价下单按钮
    //top view
    private ImageView mIvPackageLog;
    private TextView mTvPrice;

    private TextView mTvGoodsName;
    private TextView tv_copy;
    private TextView tv_combCode;
    private TextView mTvGreen;
    private TextView mTvXdyhsl;
    private TextView mTvKcdl;
    private TextView mTvYsdl;
    private TextView mTvTime;
    private TextView mTvGmzq;
    private TextView tv_memberssdName;
    private TextView tv_gmzq_max;
    private TextView mTvDydjyq;
    private TextView mTvMinEle;
    private TextView mTvMaxEle;
    private TextView mTvGoodsType;
    private RelativeLayout mRlUp;
    private RelativeLayout mRlWeiyuejin;
    private TextView mTvUp;
    private RelativeLayout mRlDown;
    private TextView mTvDown;
    private TextView mTvWeiyuejin;
    private TextView tvDisclaimers;
    private RelativeLayout rela_kcdl;
    //center view
    private LinearLayout mLlBasePackage;
    private TextView mTvBaseTitle;
    private TextView mTvIsFenshiduan;
    private TextView mTvYuedingdianliang;
    private TextView mTvZPianchafanwei;
    private TextView mTvFPianchafanwei;
    private LinearLayout mLlTop;
    private TextView mTvTop1;
    private TextView mTvTop2;
    private TextView mTvTop3;
    private LinearLayout mLlCenter;
    private TextView mTvCenter1;
    private TextView mTvCenter2;
    private TextView mTvCenter3;
    private LinearLayout mLlBottom;
    private TextView mTvBottom1;
    private TextView mTvBottom2;
    private TextView mTvBottom3;
    private LinearLayout mLlFloatingPackage;
    private TextView mTvFloatingTitle;
    private TextView mTvFloatingFenshiduan;
    private TextView mTvFloatingYuedingdianliang;
    private TextView mTvZFloatingPianchafanwei;
    private TextView mTvFFloatingPianchafanwei;
    private LinearLayout mLlFloatingTop;
    private TextView mTvFloatingTop1;
    private TextView mTvFloatingTop2;
    private TextView mTvFloatingTop3;
    private LinearLayout mLlFloatingCenter;
    private TextView mTvFloatingCenter1;
    private TextView mTvFloatingCenter2;
    private TextView mTvFloatingCenter3;
    private LinearLayout mLlFloatingBottom;
    private TextView mTvFloatingBottom1;
    private TextView mTvFloatingBottom2;
    private TextView mTvFloatingBottom3;
    private TextView mTvTitle1, mTvTitle11;
    private RelativeLayout mRlTop1, mRlTop2, mRlTop3;
    private RelativeLayout mRlCenter1, mRlCenter2, mRlCenter3;
    private RelativeLayout mRlBottom1, mRlBottom2, mRlBottom3;
    private RelativeLayout mRlFloatingTop1, mRlFloatingTop2, mRlFloatingTop3;
    private RelativeLayout mRlFloatingCenter1, mRlFloatingCenter2, mRlFloatingCenter3;
    private RelativeLayout mRlFloatingBottom1, mRlFloatingBottom2, mRlFloatingBottom3;
    //bottom view

    private LinearLayout linner_title_top, linner_title_center, linner_title_bottom;
    private LinearLayout linner_fd_title_top, linner_fd_title_center, linner_fd_title_bottom;
    private RelativeLayout rl_main_deviation_just, rl_main_deviation_negative, rl_float_deviation_just, rl_float_deviation_negative;
    private BasePopupView pop;
    private String isImmediate = "";//下单类型 0是议价下单 1立即下单  弹窗判断用
    private String mCombName;
    private boolean isShowFloPriceTipck = false;
    private MonthAdapter mMonthAdapter;
    private String[] tabTxt = {"基本参数", "套餐详情"};
    private List<View> anchorList = new ArrayList<>();
    //判读是否是scrollview主动引起的滑动，true-是，false-否，由tablayout引起的
    private boolean isScroll;
    //记录上一次位置，防止在同一内容块里滑动 重复定位到tablayout
    private int lastPos = 0;
    //监听判断最后一个模块的高度，不满一屏时让最后一个模块撑满屏幕
    private ViewTreeObserver.OnGlobalLayoutListener listener;
    private PackageBean mPackageBean;
    private PublicDifContentBean mPublicDifContentBean;
    private PublicDifContentBean mPublicDifContentBean_flo;
    private String tipickContent = "";
    private boolean ispriceOrange = false;
    private boolean isdateDifrent = false;
    private PackageInfoBean.DataDTO mMonthBean;

    @Autowired
    public boolean isBlue;//前面的价格字体是否是蓝色

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_packagedetails;
    }

    @Override
    protected PackageDetailsPresenter createPresenter() {
        return new PackageDetailsPresenter();
    }

    @Override
    protected void receiveIntentExtras() {
        super.receiveIntentExtras();
        mCombName = getIntent().getStringExtra("combName");
    }


    @Override
    public boolean isBindEventBusHere() {
        return true;
    }

    @Override
    protected void initViews() {
        super.initViews();
        onBasefindViewByIds();

        mTablayout.setTabRippleColorResource(R.color.transparent);
        //tablayout设置标签
        for (int i = 0; i < tabTxt.length; i++) {
            mTablayout.addTab(mTablayout.newTab().setText(tabTxt[i]));
        }
        mTitleBar.setTitle("商品详情");

        View top_view = getLayoutInflater().inflate(R.layout.packagedetails_top_layout, mContainer, false);
        View center_view = getLayoutInflater().inflate(R.layout.packagedetails_center_layout, mContainer, false);
//        View bottom_view = getLayoutInflater().inflate(R.layout.packagedetails_bottom_layout, mContainer, false);

        findTopViewById(top_view);
        findCenterViewById(center_view);

        anchorList.add(top_view);
        mContainer.addView(top_view);

        anchorList.add(center_view);
        mContainer.addView(center_view);

//        anchorList.add(bottom_view);
//        mContainer.addView(bottom_view);

        showDisclaimersDialog();
        setViewListener();
        mPresenter.getGoodsList(mCombName);

    }

    private void onBasefindViewByIds() {
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mTablayout = (TabLayout) findViewById(R.id.tablayout);
        mScrollView = (CustomScrollView) findViewById(R.id.scrollView);
        mContainer = (LinearLayout) findViewById(R.id.container);
        mIvAddPkNew = (ImageView) findViewById(R.id.iv_add_pk_new);
        mIvGoPk = (ImageView) findViewById(R.id.iv_go_pk);
        mLlStore = (LinearLayout) findViewById(R.id.ll_store);
        mLlCollection = (LinearLayout) findViewById(R.id.ll_collection);
        placeOrderNow = (RelativeLayout) findViewById(R.id.place_order_now);
        mIvCollection = (ImageView) findViewById(R.id.iv_collection);
        mTvCollection = (TextView) findViewById(R.id.tv_collection);
        placeOrderBargain = (RelativeLayout) findViewById(R.id.place_order_bargain);
    }


    @Override
    public void onEventMainThread(EventCenter eventCenter) {
        super.onEventMainThread(eventCenter);
        if (eventCenter.getEventCode() == ArguConstant.REFRESH_CONTRAST) {
            if (PackageContrastUtils.exists(mPackageBean.getCombId())) {
                mIvAddPkNew.setBackgroundResource(R.mipmap.mall_add_pk_newed);
            } else {
                mIvAddPkNew.setBackgroundResource(R.mipmap.mall_add_pk_new);
            }
        }

    }


    private void setViewListener() {
        mTitleBar.setRightIcon(R.mipmap.go_main, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                goMainActivity();
            }
        });

        placeOrderNow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UserManager.toLogin()) {
                    isImmediate = "1";
                    if (mPackageBean != null) {
                        if (checkTimebyBean()) {
                            mPresenter.firstCheckOrder(mPackageBean.getCombId(), isImmediate);
                        }
                    } else {
                        ToastUtils.showShort("商品信息获取失败");
                    }
                }
            }
        });

        placeOrderBargain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPackageBean != null) {
                    if (TextUtils.equals("0", mPackageBean.getConstrBarg())) {
                        ToastUtils.showShort("该商品不支持议价下单");
                    } else {
                        if (UserManager.toLogin()) {
                            if (checkTimebyBean()) {
                                isImmediate = "0";
                                mPresenter.firstCheckOrder(mPackageBean.getCombId(), isImmediate);
                            }
                        }
                    }
                } else {
                    ToastUtils.showShort("商品信息获取失败");
                }
            }
        });

        mTablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //点击标签，使scrollview滑动，isScroll置false
                isScroll = false;
                int pos = tab.getPosition();
                int top = anchorList.get(pos).getTop();
                mScrollView.smoothScrollTo(0, top);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                int pos = tab.getPosition();
                mTablayout.setScrollPosition(pos, 0, true);
                isScroll = false;
                int top = anchorList.get(pos).getTop();
                mScrollView.smoothScrollTo(0, top);
            }
        });

        mScrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //当滑动由scrollview触发时，isScroll 置true
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    isScroll = true;
                }
                return false;
            }
        });

        mScrollView.setCallbacks(new CustomScrollView.Callbacks() {
            @Override
            public void onScrollChanged(int x, int y, int oldx, int oldy) {
                if (isScroll) {
                    for (int i = tabTxt.length - 1; i >= 0; i--) {
                        //根据滑动距离，对比各模块距离父布局顶部的高度判断
                        if (y > anchorList.get(i).getTop() - 10) {
                            setScrollPos(i);
                            break;
                        }
                    }
                }
            }
        });

        mIvAddPkNew.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!UserManager.isLogin()) {
                    UserManager.toLogin();
                    return;
                }
                if (PackageContrastUtils.exists(mPackageBean.getCombId())) {
                    mIvAddPkNew.setBackgroundResource(R.mipmap.mall_add_pk_new);
                    PackageContrastUtils.deletContrast(mPackageBean.getCombId());
                } else {
                    mIvAddPkNew.setBackgroundResource(R.mipmap.mall_add_pk_newed);
                    PackageContrastUtils.addContrast(mPackageBean);
                }
                EventBus.getDefault().post(new EventCenter<>(ArguConstant.REFRESH_CONTRAST));
            }
        });

        mIvGoPk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(UserManager.toLogin()){
                    // 去对比
                    ARouter.getInstance()
                            .build(MallArouterPath.MALL_COMPARISONLIST)
                            .navigation();
                }
            }
        });

        mLlStore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                StoreInfoBean storeInfoBean = new StoreInfoBean();
                ARouter.getInstance()
                        .build(MallArouterPath.MALL_STOREHOMEPAGE)
                        .withString("membersSdId", mPackageBean.getMembersSdId())
                        .withSerializable(ArguConstant.STORE_OBJECT, storeInfoBean)
                        .navigation();
            }
        });

        rela_kcdl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPackageBean != null) {
                    if (mPackageBean.getProper() != null) {
                        pop = new XPopup.Builder(mContext)
                                .isDestroyOnDismiss(false)
                                .isViewMode(true)
                                .autoOpenSoftInput(false)
                                .asCustom(new StockPopView(PackageDetailsActivity.this, mPackageBean.getProper()))
                                .show();
                    } else {
                        ToastUtils.showShort("历史库存获取失败");
                    }
                } else {
                    ToastUtils.showShort("商品详情获取失败");
                }


            }
        });
        tvDisclaimers.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                show(false);
            }
        });

        mMonthAdapter.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, Object data) {
                //点击事件
                mMonthAdapter.setSelectPosition(position);
                PackageInfoBean.DataDTO bean = (PackageInfoBean.DataDTO) data;
                setCenterViewData(bean);
                mPresenter.getSchemeCombBySchemeIdYH(bean.getMainSchemeId(), bean.getFloSchemeId());
                mPresenter.getPriceAndPriceDetail(bean.getMainSchemeId(), bean.getFloSchemeId());
            }
        });
    }

    private void setViewData() {
        if (PackageContrastUtils.exists(mPackageBean.getCombId())) {
            mIvAddPkNew.setBackgroundResource(R.mipmap.mall_add_pk_newed);
        } else {
            mIvAddPkNew.setBackgroundResource(R.mipmap.mall_add_pk_new);
        }

        if ("00".equals(mPackageBean.getUstatus())) {////收藏状态： 00未收藏 01 已收藏
            mIvCollection.setBackgroundResource(R.mipmap.mall_goods_info_collection);
            mTvCollection.setTextColor(Color.parseColor("#999999"));

            mLlCollection.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //调用收藏接口
                    if (UserManager.toLogin()) {
                        mPresenter.addUserPackageCollection("", mPackageBean.getMembersSdId(), mPackageBean.getMembersSdName(),
                                mPackageBean.getCombId(), mPackageBean.getCombName());
                    }
                }
            });
        } else {
            mIvCollection.setBackgroundResource(R.mipmap.mall_goods_info_collectioned);
            mTvCollection.setTextColor(Color.parseColor("#3274F0"));

            mLlCollection.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //调用取消收藏接口
                    mPresenter.deletePackageById(mPackageBean.getCombId(), mPackageBean.getMembersSdId());
                }
            });
        }
    }

    /**
     * 免责声明弹窗
     */
    private void showDisclaimersDialog() {
        SPUtils spUtils = SPUtils.getInstance();
        if (!isBlue) {
            boolean is7DayNotRemind = spUtils.getBoolean("is7DayNotRemind", false);//是否一周之内不提醒  true不提醒 false 提醒
            if (is7DayNotRemind) {//不提醒
                long day = Math.abs(TimeUtils.getTimeSpanByNow(spUtils.getLong("DisclaimersDate"), TimeConstants.DAY));
                if (day > 7) {//提醒
                    show(true);
                }
            } else {//提醒
                show(true);
            }
        }
    }

    private void show(boolean isShowCheck) {
        new XPopup.Builder(mContext)
                .asCustom(new PackageDetailsPopView(PackageDetailsActivity.this, new PackageDetailsPopView.OnListener() {
                    @Override
                    public void onPositiveClick(PackageDetailsPopView pop, boolean ischeck) {
                        SPUtils spUtils = SPUtils.getInstance();
                        spUtils.put("is7DayNotRemind", ischeck);
                        if (ischeck) {
                            spUtils.put("DisclaimersDate", System.currentTimeMillis());
                        }
                    }
                }, "近期历史参考价", "商品上方显示价格，为依据近一年历史电价信息及典型曲线计算所得的参考价，非最终结算电价。且未考虑电量偏差，如需测算请进行套餐试算。", "一周内不再提示", "知道了", isShowCheck, false))
                .show();
    }

    private void findTopViewById(View top_view) {
        mIvPackageLog = (ImageView) top_view.findViewById(R.id.iv_package_log);
        mTvPrice = (TextView) top_view.findViewById(R.id.tv_price);
        tv_combCode = (TextView) top_view.findViewById(R.id.tv_combCode);
        tv_copy = (TextView) top_view.findViewById(R.id.tv_copy);
        mTvGoodsName = (TextView) top_view.findViewById(R.id.tv_goods_name);
        mTvGreen = (TextView) top_view.findViewById(R.id.tv_green);
        mTvXdyhsl = (TextView) top_view.findViewById(R.id.tv_xdyhsl);
        mTvKcdl = (TextView) top_view.findViewById(R.id.tv_kcdl);
        mTvYsdl = (TextView) top_view.findViewById(R.id.tv_ysdl);
        mTvTime = (TextView) top_view.findViewById(R.id.tv_time);
        mTvGmzq = (TextView) top_view.findViewById(R.id.tv_gmzq);
        tv_memberssdName = (TextView) top_view.findViewById(R.id.tv_memberssdName);
        tv_gmzq_max = (TextView) top_view.findViewById(R.id.tv_gmzq_max);
        mTvDydjyq = (TextView) top_view.findViewById(R.id.tv_dydjyq);
        mTvMinEle = (TextView) top_view.findViewById(R.id.tv_min_ele);
        mTvMaxEle = (TextView) top_view.findViewById(R.id.tv_max_ele);
        mTvGoodsType = (TextView) top_view.findViewById(R.id.tv_goods_type);
        mRlUp = (RelativeLayout) top_view.findViewById(R.id.rl_up);
        mTvUp = (TextView) top_view.findViewById(R.id.tv_up);
        mRlDown = (RelativeLayout) top_view.findViewById(R.id.rl_down);
        mTvDown = (TextView) top_view.findViewById(R.id.tv_down);
        mRlWeiyuejin = (RelativeLayout) top_view.findViewById(R.id.rl_weiyuejin);
        mTvWeiyuejin = (TextView) top_view.findViewById(R.id.tv_weiyuejin);
        tvDisclaimers = (TextView) top_view.findViewById(R.id.tvDisclaimers);
        rela_kcdl = (RelativeLayout) top_view.findViewById(R.id.rela_kcdl);
        tv_copy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String combCode = tv_combCode.getText().toString();
                ClipboardUtils.copyText(combCode);
                ToastUtils.showShort("已经复制到剪贴板");
            }
        });
    }


    private void findCenterViewById(View center_view) {
        mRlContent = (RecyclerView) center_view.findViewById(R.id.rl_content);
        mLlBasePackage = (LinearLayout) center_view.findViewById(R.id.ll_base_package);
        mTvBaseTitle = (TextView) center_view.findViewById(R.id.tv_base_title);
        mTvIsFenshiduan = (TextView) center_view.findViewById(R.id.tv_is_fenshiduan);
        mTvYuedingdianliang = (TextView) center_view.findViewById(R.id.tv_yuedingdianliang);
        mTvZPianchafanwei = (TextView) center_view.findViewById(R.id.tv_z_pianchafanwei);
        mTvFPianchafanwei = (TextView) center_view.findViewById(R.id.tv_f_pianchafanwei);
        mLlTop = (LinearLayout) center_view.findViewById(R.id.ll_top);
        mRlTop1 = (RelativeLayout) center_view.findViewById(R.id.rl_top_1);
        mRlTop2 = (RelativeLayout) center_view.findViewById(R.id.rl_top_2);
        mRlTop3 = (RelativeLayout) center_view.findViewById(R.id.rl_top_3);
        mTvTop1 = (TextView) center_view.findViewById(R.id.tv_top_1);
        mTvTop2 = (TextView) center_view.findViewById(R.id.tv_top_2);
        mTvTop3 = (TextView) center_view.findViewById(R.id.tv_top_3);
        mLlCenter = (LinearLayout) center_view.findViewById(R.id.ll_center);
        mRlCenter1 = (RelativeLayout) center_view.findViewById(R.id.rl_center_1);
        mRlCenter2 = (RelativeLayout) center_view.findViewById(R.id.rl_center_2);
        mRlCenter3 = (RelativeLayout) center_view.findViewById(R.id.rl_center_3);
        mTvCenter1 = (TextView) center_view.findViewById(R.id.tv_center_1);
        mTvCenter2 = (TextView) center_view.findViewById(R.id.tv_center_2);
        mTvCenter3 = (TextView) center_view.findViewById(R.id.tv_center_3);
        mLlBottom = (LinearLayout) center_view.findViewById(R.id.ll_bottom);
        mRlBottom1 = (RelativeLayout) center_view.findViewById(R.id.rl_bottom_1);
        mRlBottom2 = (RelativeLayout) center_view.findViewById(R.id.rl_bottom_2);
        mRlBottom3 = (RelativeLayout) center_view.findViewById(R.id.rl_bottom_3);
        mTvBottom1 = (TextView) center_view.findViewById(R.id.tv_bottom_1);
        mTvBottom2 = (TextView) center_view.findViewById(R.id.tv_bottom_2);
        mTvBottom3 = (TextView) center_view.findViewById(R.id.tv_bottom_3);
        mLlFloatingPackage = (LinearLayout) center_view.findViewById(R.id.ll_floating_package);
        mTvFloatingTitle = (TextView) center_view.findViewById(R.id.tv_floating_title);
        mTvFloatingFenshiduan = (TextView) center_view.findViewById(R.id.tv_floating__fenshiduan);
        mTvFloatingYuedingdianliang = (TextView) center_view.findViewById(R.id.tv_floating_yuedingdianliang);
        mTvZFloatingPianchafanwei = (TextView) center_view.findViewById(R.id.tv_z_floating_pianchafanwei);
        mTvFFloatingPianchafanwei = (TextView) center_view.findViewById(R.id.tv_f_floating_pianchafanwei);
        mLlFloatingTop = (LinearLayout) center_view.findViewById(R.id.ll_floating_top);
        mRlFloatingTop1 = (RelativeLayout) center_view.findViewById(R.id.rl_floating_top_1);
        mRlFloatingTop2 = (RelativeLayout) center_view.findViewById(R.id.rl_floating_top_2);
        mRlFloatingTop3 = (RelativeLayout) center_view.findViewById(R.id.rl_floating_top_3);
        mTvFloatingTop1 = (TextView) center_view.findViewById(R.id.tv_floating_top_1);
        mTvFloatingTop2 = (TextView) center_view.findViewById(R.id.tv_floating_top_2);
        mTvFloatingTop3 = (TextView) center_view.findViewById(R.id.tv_floating_top_3);
        mLlFloatingCenter = (LinearLayout) center_view.findViewById(R.id.ll_floating_center);
        mRlFloatingCenter1 = (RelativeLayout) center_view.findViewById(R.id.rl_floating_center_1);
        mRlFloatingCenter2 = (RelativeLayout) center_view.findViewById(R.id.rl_floating_center_2);
        mRlFloatingCenter3 = (RelativeLayout) center_view.findViewById(R.id.rl_floating_center_3);
        mTvFloatingCenter1 = (TextView) center_view.findViewById(R.id.tv_floating_center_1);
        mTvFloatingCenter2 = (TextView) center_view.findViewById(R.id.tv_floating_center_2);
        mTvFloatingCenter3 = (TextView) center_view.findViewById(R.id.tv_floating_center_3);
        mLlFloatingBottom = (LinearLayout) center_view.findViewById(R.id.ll_floating_bottom);
        mRlFloatingBottom1 = (RelativeLayout) center_view.findViewById(R.id.rl_floating_bottom_1);
        mRlFloatingBottom2 = (RelativeLayout) center_view.findViewById(R.id.rl_floating_bottom_2);
        mRlFloatingBottom3 = (RelativeLayout) center_view.findViewById(R.id.rl_floating_bottom_3);
        mTvFloatingBottom1 = (TextView) center_view.findViewById(R.id.tv_floating_bottom_1);
        mTvFloatingBottom2 = (TextView) center_view.findViewById(R.id.tv_floating_bottom_2);
        mTvFloatingBottom3 = (TextView) center_view.findViewById(R.id.tv_floating_bottom_3);
        mTvTitle1 = (TextView) center_view.findViewById(R.id.tv_title1);
        mTvTitle11 = (TextView) center_view.findViewById(R.id.tv_title11);

        linner_title_top = (LinearLayout) center_view.findViewById(R.id.linner_title_top);
        linner_title_center = (LinearLayout) center_view.findViewById(R.id.linner_title_center);
        linner_title_bottom = (LinearLayout) center_view.findViewById(R.id.linner_title_bottom);

        linner_fd_title_top = (LinearLayout) center_view.findViewById(R.id.linner_fd_title_top);
        linner_fd_title_center = (LinearLayout) center_view.findViewById(R.id.linner_fd_title_center);
        linner_fd_title_bottom = (LinearLayout) center_view.findViewById(R.id.linner_fd_title_bottom);
        rl_main_deviation_just = center_view.findViewById(R.id.rl_main_deviation_just);
        rl_main_deviation_negative = center_view.findViewById(R.id.rl_main_deviation_negative);

        rl_float_deviation_just = center_view.findViewById(R.id.rl_float_deviation_just);
        rl_float_deviation_negative = center_view.findViewById(R.id.rl_float_deviation_negative);


        linner_title_top.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPriceTipick();
            }
        });
        linner_title_center.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPriceTipick();
            }
        });
        linner_title_bottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPriceTipick();
            }
        });


        linner_fd_title_top.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPriceTipick();
            }
        });
        linner_fd_title_center.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPriceTipick();
            }
        });
        linner_fd_title_bottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showPriceTipick();
            }
        });


        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        mRlContent.setLayoutManager(mLayoutManager);
        mRlContent.setItemAnimator(new DefaultItemAnimator());
        mMonthAdapter = new MonthAdapter(mContext);
        mRlContent.setAdapter(mMonthAdapter);
    }

    private void showPriceTipick() {
//        new XPopup.Builder(mContext)
//                .isDestroyOnDismiss(false)
//                .isViewMode(true)
//                .autoOpenSoftInput(false)
//                .asCustom(new PriceTipickPopView(PackageDetailsActivity.this))
//                .show();
    }

    /**
     * tablayout对应标签的切换
     *
     * @param newPos
     */
    private void setScrollPos(int newPos) {
        if (lastPos != newPos) {
            //该方法不会触发tablayout 的onTabSelected 监听
            mTablayout.setScrollPosition(newPos, 0, true);
        }
        lastPos = newPos;
    }

    @Override
    public void queryGoodsSuccess(MallGoodsBean response) {
        if (response != null) {
            if (response.getCode() == 200) {
                if (response.getData() != null) {
                    if (!response.getData().getData().isEmpty()) {
                        mPackageBean = response.getData().getData().get(0);
                        mPresenter.getPackageDetails(mPackageBean.getCombId());
                        mPresenter.getPackageInfo(mPackageBean.getCombId());
                        setViewData();
                        PackageContrastUtils.addFootprint(mPackageBean);
                    } else {
                        ToastUtils.showLong("商品不存在或已下架");
                        EventBus.getDefault().post(new EventCenter<>(ArguConstant.REFRESH_GOODS_LIST));
                        close();
//                        mPresenter.getGoodsDetails(mCombName);
                    }
                } else {
                    ToastUtils.showLong("商品不存在或已下架");
                    EventBus.getDefault().post(new EventCenter<>(ArguConstant.REFRESH_GOODS_LIST));
                    close();
//                    mPresenter.getGoodsDetails(mCombName);
                }
            } else {
                if (!TextUtils.isEmpty(response.getMsg())) {
                    ToastUtils.showShort(response.getMsg());
                }
            }
        }
    }

    private void close() {
        new CountDownTimer(2000, 1000) {

            @Override
            public void onTick(long l) {

            }

            @Override
            public void onFinish() {
                finish();
            }
        }.start();
    }

    @Override
    public void queryGoodsFailed() {

    }

    @Override
    public void getGoodsDetailsSuccess(PackageBean response) {
        if (null != response) {
            mPackageBean = response;
            mPresenter.getPackageDetails(mPackageBean.getCombId());
            mPresenter.getPackageInfo(mPackageBean.getCombId());
            setViewData();
            PackageContrastUtils.addFootprint(mPackageBean);
        }
    }

    @Override
    public void getGoodsDetailsFailed() {

    }

    @Override
    public void queryPackageDetailsSuccess(PackageDetailsBean response) {
        if (response != null) {
            if ("200".equals(response.getCode())) {
                //-----开始给控件设置值
                PackageDetailsBean.DataDTO bean = response.getData();
                if (bean != null && !TextUtils.isEmpty(bean.getContactPhone())) {
                    mTitleBar.setRight1Icon(R.mipmap.ic_phone, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DialogUtil.showCallPhone(mContext, bean.getContactPhone());
                        }
                    });
                }
                String img_url = HttpInterConst.BASEURL_IMG + mPackageBean.getFileId();
                Glide.with(mContext).load(img_url).placeholder(R.mipmap.deft_goods).error(R.mipmap.deft_goods).into(mIvPackageLog);
                mPackageBean.setBuyEndMonth(response.getData().getBuyEndMonth());
                mPackageBean.setBuyStartMonth(response.getData().getBuyStartMonth());
//                mTvPrice.setText(BigDecimalUtils.onKeep2Decimal(mPackageBean.getPrice()));
                mTvPrice.setText(mPackageBean.getPrice());

                if (TextUtils.isEmpty(response.getData().getConstrFee())) {
                    mRlWeiyuejin.setVisibility(View.GONE);
                } else {
                    mRlWeiyuejin.setVisibility(View.VISIBLE);
                    mTvWeiyuejin.setText(BigDecimalUtils.onKeep5Decimal_divide(response.getData().getConstrFee()) + "元/度");
                }

                if ("1".equals(bean.getPNum()) && ("03".equals(bean.getMainType()) || "04".equals(bean.getMainType())) &&
                        "0".equals(bean.getMainItemType()) &&
                        ("0".equals(bean.getMainDifType()) || TextUtils.isEmpty(bean.getMainDifType()))
                ) {//单一套餐&&不分时段&&固定价格&&没有浮动价差
                    //蓝色
                    mTvPrice.setTextColor(Color.parseColor("#0092FF"));
                } else {
                    //橙色
                    mTvPrice.setTextColor(Color.parseColor("#FFA500"));
                    ispriceOrange = true;
                }
                tv_combCode.setText(mPackageBean.getCombCode());
//                mTvGoodsName.setText(mPackageBean.getSellingPoint());
                mTvGoodsName.setText(TextUtil.getName(mPackageBean.getSellingPoint(), mPackageBean.getCreditRating()));
                mTvGreen.setText(EnumUtils.getGreenLeft(bean.getConstrRel()) + "  " + EnumUtils.getGreenCenter(bean.getConstrMod()) + "  " + EnumUtils.getGreenRight(bean.getConstrBarg()));

                mTvXdyhsl.setText(bean.getPurNum() + "");//下单用户(个)
                mTvKcdl.setText(mPackageBean.getStockInfo());//库存电量(MWh)
                mTvYsdl.setText("0.00000".equals(bean.getSoldEnergy()) ? "0" : BigDecimalUtils.onKeep3Decimal(bean.getSoldEnergy()));//已售电量(MWh)

                mTvTime.setText(DateUtils.getStrng_to_Times_ymd_1(bean.getEffectiveDate()) + "~" + DateUtils.getStrng_to_Times_ymd_1(bean.getInvalidDate()));
                if (TextUtils.equals(DateUtils.getStrng_to_Times_ymd_1(bean.getEffectiveDate()), DateUtils.getStrng_to_Times_ymd_1(bean.getInvalidDate()))) {
                    isdateDifrent = false;
                } else {
                    isdateDifrent = true;
                }
                int maxMonth = getMaxMonth();
                if ("04".equals(bean.getConstrMinCyc())) {
                    mTvGmzq.setText(maxMonth + "自然月");
                    tv_gmzq_max.setText(maxMonth + "自然月");
                    mPackageBean.setConstrMax(maxMonth+"");
//                    mTvGmzq.setText(EnumUtils.getConstrMin(bean.getConstrMinCyc()));
//                    tv_gmzq_max.setText(EnumUtils.getConstrMin(bean.getConstrMinCyc()));
                } else {
                    mTvGmzq.setText(bean.getConstrMin() + EnumUtils.getConstrMin(bean.getConstrMinCyc()));
                    if(TextUtils.isEmpty(bean.getConstrMax())){
                        tv_gmzq_max.setText(maxMonth + EnumUtils.getConstrMin(bean.getConstrMinCyc()));
                        mPackageBean.setConstrMax(maxMonth+"");
                    }else{
                        tv_gmzq_max.setText(bean.getConstrMax() + EnumUtils.getConstrMin(bean.getConstrMinCyc()));
                    }
//
                }
                tv_memberssdName.setText(mPackageBean.getMembersSdName());
                if ("1".equals(mPackageBean.getpNum()) && ("03".equals(mPackageBean.getMainType()) || "04".equals(mPackageBean.getMainType())) &&
                        "0".equals(mPackageBean.getMainItemType()) &&
                        ("0".equals(mPackageBean.getMainDifType()) || TextUtils.isEmpty(mPackageBean.getMainDifType()))
                ) {//单一套餐&&不分时段&&固定价格&&没有浮动价差
                    //蓝色
                    tvDisclaimers.setVisibility(View.GONE);
                }


                mTvDydjyq.setText(TextUtils.isEmpty(bean.getVoltageLevel()) ? "--" : bean.getVoltageLevel());//电压等级要求
                mTvMinEle.setText(TextUtils.isEmpty(bean.getUserEnergy()) ? "--" : "0.00000".equals(bean.getUserEnergy()) ? "0MWh" : BigDecimalUtils.onKeep3Decimal(bean.getUserEnergy()) + "MWh");//最小用电量门槛
                mTvMaxEle.setText(TextUtils.isEmpty(bean.getUserEnergyMax()) ? "--" : "0.00000".equals(bean.getUserEnergyMax()) ? "0MWh" : BigDecimalUtils.onKeep3Decimal(bean.getUserEnergyMax()) + "MWh");//最大用电量门槛

                if ("1".equals(bean.getPNum())) {
                    mTvGoodsType.setText("基础价格套餐");
                    mRlUp.setVisibility(View.GONE);
                    mRlDown.setVisibility(View.GONE);
                    mLlBasePackage.setVisibility(View.VISIBLE);
                    mLlFloatingPackage.setVisibility(View.GONE);
                    mTvBaseTitle.setText("基础价格套餐");
                } else {
                    mLlBasePackage.setVisibility(View.VISIBLE);
                    mLlFloatingPackage.setVisibility(View.VISIBLE);
                    mTvGoodsType.setText("组合价格套餐(基准套餐+浮动套餐)");
                    mRlUp.setVisibility(View.VISIBLE);
                    mRlDown.setVisibility(View.VISIBLE);
                    mTvUp.setText(TextUtils.isEmpty(mPackageBean.getSchemeRatio1()) ? "" : "K1=" + mPackageBean.getSchemeRatio1() + "%");
                    mTvDown.setText(TextUtils.isEmpty(mPackageBean.getSchemeRatio2()) ? "" : "K2=" + mPackageBean.getSchemeRatio2() + "%");
                    mTvBaseTitle.setText("基准套餐");
                }
                //-----结束给控件设置值
            }
        }
    }

    @Override
    public void queryPackageDetailsFailed() {

    }

    @Override
    public void queryMonthListSuccess(PackageInfoBean response) {
        if (response != null) {
            if (response.getCode() == 200) {
                if (response.getData() != null) {
                    if (response.getData().size() > 0) {
                        mMonthAdapter.addDatas(response.getData());
                        mPresenter.getSchemeCombBySchemeIdYH(response.getData().get(0).getMainSchemeId(), response.getData().get(0).getFloSchemeId());
                        mPresenter.getPriceAndPriceDetail(response.getData().get(0).getMainSchemeId(), response.getData().get(0).getFloSchemeId());
                        setCenterViewData(response.getData().get(0));
                    }
                }
            }
        }
    }

    private void setCenterViewData(PackageInfoBean.DataDTO bean) {
        mMonthBean = bean;
        //基准或者单一
        String mainType = TextUtils.isEmpty(bean.getMainType()) ? "" : bean.getMainType();
        switch (bean.getMainType()) {
            case "01"://分时分电量
                mTvIsFenshiduan.setText("是");
                mTvYuedingdianliang.setText("是");
                mTvTitle11.setText("约定电量电价参数");
                break;
            case "02"://分时不分电量
                mTvIsFenshiduan.setText("是");
                mTvYuedingdianliang.setText("否");
//                mTvTitle11.setText("电价参数");
                mTvTitle11.setText("用电量电价参数");
                break;
            case "03"://不分时分电量
                mTvIsFenshiduan.setText("否");
                mTvYuedingdianliang.setText("是");
                mTvTitle11.setText("约定电量电价参数");
                break;
            case "04"://不分时不分电量
                mTvIsFenshiduan.setText("否");
                mTvYuedingdianliang.setText("否");
//                mTvTitle11.setText("电价参数");
                mTvTitle11.setText("用电量电价参数");
                break;
        }

        if ("02".equals(mainType) || "04".equals(mainType)) {
            mLlCenter.setVisibility(View.GONE);
            mLlBottom.setVisibility(View.GONE);
            rl_main_deviation_just.setVisibility(View.GONE);
            rl_main_deviation_negative.setVisibility(View.GONE);
        } else {
            mLlCenter.setVisibility(View.VISIBLE);
            mLlBottom.setVisibility(View.VISIBLE);
            rl_main_deviation_just.setVisibility(View.VISIBLE);
            rl_main_deviation_negative.setVisibility(View.VISIBLE);
        }

        String json = bean.getMainDifContent();
        if (!TextUtils.isEmpty(json)) {
            mPublicDifContentBean = GsonUtils.fromJson(json, PublicDifContentBean.class);

            mRlTop2.setVisibility(View.GONE);
            mRlTop3.setVisibility(View.GONE);
            if (!mPublicDifContentBean.getEdata().isEmpty()) {
                setViewData(mRlTop2, mRlTop3, mTvTop2, mTvTop3, mPublicDifContentBean.getEdata());
            }

            mRlCenter2.setVisibility(View.GONE);
            mRlCenter3.setVisibility(View.GONE);
            if (!mPublicDifContentBean.getPldata().isEmpty()) {
                setViewData(mRlCenter2, mRlCenter3, mTvCenter2, mTvCenter3, mPublicDifContentBean.getPldata());
            }

            mRlBottom2.setVisibility(View.GONE);
            mRlBottom3.setVisibility(View.GONE);
            if (!mPublicDifContentBean.getNddata().isEmpty()) {
                setViewData(mRlBottom2, mRlBottom3, mTvBottom2, mTvBottom3, mPublicDifContentBean.getNddata());
            }
        }

        //浮动
        String floType = TextUtils.isEmpty(bean.getFloType()) ? "" : bean.getFloType();
        switch (floType) {
            case "01"://分时分电量
                mTvFloatingFenshiduan.setText("是");
                mTvFloatingYuedingdianliang.setText("是");
                mTvTitle1.setText("约定电量电价参数");
                break;
            case "02"://分时不分电量
                mTvFloatingFenshiduan.setText("是");
                mTvFloatingYuedingdianliang.setText("否");
                mTvTitle1.setText("用电量电价参数");
                break;
            case "03"://不分时分电量
                mTvFloatingFenshiduan.setText("否");
                mTvFloatingYuedingdianliang.setText("是");
                mTvTitle1.setText("约定电量电价参数");
                break;
            case "04"://不分时不分电量
                mTvFloatingFenshiduan.setText("否");
                mTvFloatingYuedingdianliang.setText("否");
                mTvTitle1.setText("用电量电价参数");
                break;
            default:
                break;
        }

        if ("02".equals(floType) || "04".equals(floType)) {
            mLlFloatingCenter.setVisibility(View.GONE);
            mLlFloatingBottom.setVisibility(View.GONE);
            rl_float_deviation_just.setVisibility(View.GONE);
            rl_float_deviation_negative.setVisibility(View.GONE);
        } else {
            mLlFloatingCenter.setVisibility(View.VISIBLE);
            mLlFloatingBottom.setVisibility(View.VISIBLE);
            rl_float_deviation_just.setVisibility(View.VISIBLE);
            rl_float_deviation_negative.setVisibility(View.VISIBLE);
        }

        String json_flo = bean.getFloDifContent();
        if (!TextUtils.isEmpty(json_flo)) {
            mPublicDifContentBean_flo = GsonUtils.fromJson(json_flo, PublicDifContentBean.class);

            mRlFloatingTop2.setVisibility(View.GONE);
            mRlFloatingTop3.setVisibility(View.GONE);
            if (!mPublicDifContentBean_flo.getEdata().isEmpty()) {
                setViewData(mRlFloatingTop2, mRlFloatingTop3, mTvFloatingTop2, mTvFloatingTop3, mPublicDifContentBean_flo.getEdata());
            }

            mRlFloatingCenter2.setVisibility(View.GONE);
            mRlFloatingCenter3.setVisibility(View.GONE);
            if (!mPublicDifContentBean_flo.getPldata().isEmpty()) {
                setViewData(mRlFloatingCenter2, mRlFloatingCenter3, mTvFloatingCenter2, mTvFloatingCenter3, mPublicDifContentBean_flo.getPldata());
            }

            mRlFloatingBottom2.setVisibility(View.GONE);
            mRlFloatingBottom3.setVisibility(View.GONE);
            if (!mPublicDifContentBean_flo.getNddata().isEmpty()) {
                setViewData(mRlFloatingBottom2, mRlFloatingBottom3, mTvFloatingBottom2, mTvFloatingBottom3, mPublicDifContentBean_flo.getNddata());
            }
        }
    }

    public void setViewData(RelativeLayout rl1, RelativeLayout rl2, TextView tv1, TextView tv2, List<PublicDifContentBean.PublicNameValueBean> list) {
        for (PublicDifContentBean.PublicNameValueBean publicNameValueBean : list) {
            if ("约定价差".equals(publicNameValueBean.getName())) {
                rl1.setVisibility(View.VISIBLE);
                String value = BigDecimalUtils.onKeep5Decimal_divide(publicNameValueBean.getValue());
                tv1.setText(value + "元/度");
            } else {
                rl2.setVisibility(View.VISIBLE);
                String value = BigDecimalUtils.onKeep3Decimal(publicNameValueBean.getValue());
                String result = "";
                result += publicNameValueBean.getName() + "x" + value + "%";
                tv2.setText(result);
            }
        }
    }

    @Override
    public void queryMonthListFailed() {

    }

    @Override
    public void queryPriceListSuccess(SchemeCombBySchemeIdYHBean response) {
        if (response != null) {
            if (response.getCode() == 200) {
                if (response.getData() != null) {
                    if (response.getData().getMainScheme() != null) {
                        if (response.getData().getMainScheme().size() > 0) {

                            String eItemId = response.getData().getMainScheme().get(0).geteItemId();//约定电量 / 计量电量电价ID，根据D111判断是否为约定价格
                            String eItemName = response.getData().getMainScheme().get(0).geteItemName();
                            String eItemValue = response.getData().getMainScheme().get(0).geteItemValue();
                            setViewData(mRlTop1, mTvTop1, "1", eItemId, mMonthBean.getMainType(), eItemName, eItemValue, response.getData().getMainScheme());

                            String plItemId = response.getData().getMainScheme().get(0).getPlItemId();//正偏差电量电价ID，根据D111判断是否为约定价格
                            String plItemName = response.getData().getMainScheme().get(0).getPlItemName();
                            String plItemValue = response.getData().getMainScheme().get(0).getPlItemValue();
                            setViewData(mRlCenter1, mTvCenter1, "2", plItemId, mMonthBean.getMainType(), plItemName, plItemValue, response.getData().getMainScheme());

                            String ndItemId = response.getData().getMainScheme().get(0).getNdItemId();//正偏差电量电价ID，根据D111判断是否为约定价格
                            String ndItemName = response.getData().getMainScheme().get(0).getNdItemName();
                            String ndItemValue = response.getData().getMainScheme().get(0).getNdItemValue();
                            setViewData(mRlBottom1, mTvBottom1, "3", ndItemId, mMonthBean.getMainType(), ndItemName, ndItemValue, response.getData().getMainScheme());

                            String ndRange = TextUtils.isEmpty(response.getData().getMainScheme().get(0).getNdRange()) ?
                                    "--" : BigDecimalUtils.onKeep2Decimal_new(response.getData().getMainScheme().get(0).getNdRange()) + "%";
                            String plRange = TextUtils.isEmpty(response.getData().getMainScheme().get(0).getPlRange()) ?
                                    "--" : BigDecimalUtils.onKeep2Decimal_new(response.getData().getMainScheme().get(0).getPlRange()) + "%";

                            mTvZPianchafanwei.setText(plRange);
                            mTvFPianchafanwei.setText(ndRange);
                        } else {
                            mTvZPianchafanwei.setText("--");
                            mTvFPianchafanwei.setText("--");
                        }
                    }

                    if (response.getData().getFloScheme() != null) {
                        if (response.getData().getFloScheme().size() > 0) {

                            String eItemId = response.getData().getFloScheme().get(0).geteItemId();//约定电量 / 计量电量电价ID，根据D111判断是否为约定价格
                            String eItemName = response.getData().getFloScheme().get(0).geteItemName();
                            String eItemValue = response.getData().getFloScheme().get(0).geteItemValue();
                            setViewData(mRlFloatingTop1, mTvFloatingTop1, "1", eItemId, mMonthBean.getFloType(), eItemName, eItemValue, response.getData().getFloScheme());

                            String plItemId = response.getData().getFloScheme().get(0).getPlItemId();//约定电量 / 计量电量电价ID，根据D111判断是否为约定价格
                            String plItemName = response.getData().getFloScheme().get(0).getPlItemName();
                            String plItemValue = response.getData().getFloScheme().get(0).getPlItemValue();
                            setViewData(mRlFloatingCenter1, mTvFloatingCenter1, "2", plItemId, mMonthBean.getFloType(), plItemName, plItemValue, response.getData().getFloScheme());

                            String ndItemId = response.getData().getFloScheme().get(0).getNdItemId();//约定电量 / 计量电量电价ID，根据D111判断是否为约定价格
                            String ndItemName = response.getData().getFloScheme().get(0).getNdItemName();
                            String ndItemValue = response.getData().getFloScheme().get(0).getNdItemValue();
                            setViewData(mRlFloatingBottom1, mTvFloatingBottom1, "3", ndItemId, mMonthBean.getFloType(), ndItemName, ndItemValue, response.getData().getFloScheme());

                            String ndRange = TextUtils.isEmpty(response.getData().getFloScheme().get(0).getNdRange()) ?
                                    "--" : BigDecimalUtils.onKeep2Decimal_new(response.getData().getFloScheme().get(0).getNdRange()) + "%";
                            String plRange = TextUtils.isEmpty(response.getData().getFloScheme().get(0).getPlRange()) ?
                                    "--" : BigDecimalUtils.onKeep2Decimal_new(response.getData().getFloScheme().get(0).getPlRange()) + "%";
                            mTvZFloatingPianchafanwei.setText(plRange);
                            mTvFFloatingPianchafanwei.setText(ndRange);
                        } else {
                            mTvZFloatingPianchafanwei.setText("--");
                            mTvFFloatingPianchafanwei.setText("--");
                        }
                    }
                }
            }
        }
    }

    private void setViewData(RelativeLayout relativeLayout, TextView textView, String type, String itemId, String mainType, String itemName,
                             String itemValue, List<FloMainSchemeBean> floMainSchemeBeanList) {
        if ("D111".equals(itemId)) {
            if ("01".equals(mainType) || "02".equals(mainType)) {
                //分时段 显示
                if (TextUtils.isEmpty(itemName)) {
                    relativeLayout.setVisibility(View.GONE);
                } else {
                    relativeLayout.setVisibility(View.VISIBLE);
                    textView.setText(itemName);
                    //蓝色下划线可点击
                    textView.setTextColor(Color.parseColor("#0092FF"));
                    textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            List<String> list = new ArrayList<>();
                            for (FloMainSchemeBean bean : floMainSchemeBeanList) {
                                if ("1".equals(type)) {
                                    list.add(BigDecimalUtils.onKeep5Decimal_divide(bean.geteItemValue()));
                                }
                                if ("2".equals(type)) {
                                    list.add(BigDecimalUtils.onKeep5Decimal_divide(bean.getPlItemValue()));
                                }
                                if ("3".equals(type)) {
                                    list.add(BigDecimalUtils.onKeep5Decimal_divide(bean.getNdItemValue()));
                                }
                            }
                            DialogUtil.showLineChartDialog(mContext, list);
                        }
                    });
                }
            } else {
                //不分时段 显示数字
                if (TextUtils.isEmpty(itemValue)) {
                    relativeLayout.setVisibility(View.GONE);
                } else {
                    relativeLayout.setVisibility(View.VISIBLE);
                    textView.setText(BigDecimalUtils.onKeep5Decimal_divide(itemValue) + "元/度");
                    textView.setTextColor(Color.parseColor("#464646"));
                }
            }
        } else {
            if (TextUtils.isEmpty(itemName)) {
                relativeLayout.setVisibility(View.GONE);
            } else {
                relativeLayout.setVisibility(View.VISIBLE);
                textView.setText(itemName);
                textView.setTextColor(Color.parseColor("#464646"));
            }
            if (!TextUtils.isEmpty(itemId)) {
                isShowFloPriceTipck = true;
            }
        }

    }

    @Override
    public void queryPriceListFailed() {

    }

    @Override
    public void queryDetailSuccess(PriceAndPriceDetailBean response) {
        if (response != null) {
            if (response.getCode() == 200) {
                if (response.getData() != null) {
                    if (!response.getData().getMainScheme().isEmpty()) {
                        if (!TextUtils.isEmpty(response.getData().getMainScheme().get(0).getConfigId()) && !TextUtils.equals("E111", response.getData().getMainScheme().get(0).getConfigId())) {
                            isShowFloPriceTipck = true;
                        }
                    }
                    if (!response.getData().getFloScheme().isEmpty()) {
                        if (!TextUtils.isEmpty(response.getData().getFloScheme().get(0).getConfigId()) && !TextUtils.equals("E111", response.getData().getFloScheme().get(0).getConfigId())) {
                            isShowFloPriceTipck = true;
                        }
                    }
                }
            }
        }
    }

    @Override
    public void queryDetailFailed() {

    }

    @Override
    public void addCollectionSuccess(BaseResponse response) {
        if (response != null) {
            if (response.isSuccess()) {
                mIvCollection.setBackgroundResource(R.mipmap.mall_goods_info_collectioned);
                mTvCollection.setTextColor(Color.parseColor("#3274F0"));
                mPackageBean.setUstatus("01");
                mLlCollection.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //调用取消收藏接口
                        mPresenter.deletePackageById(mPackageBean.getCombId(), mPackageBean.getMembersSdId());
                    }
                });
            }
        }
    }

    @Override
    public void addCollectionFailed() {

    }

    @Override
    public void deleteCollectionSuccess(BaseResponse response) {
        if (response != null) {
            if (response.isSuccess()) {
                mIvCollection.setBackgroundResource(R.mipmap.mall_goods_info_collection);
                mTvCollection.setTextColor(Color.parseColor("#999999"));
                mPackageBean.setUstatus("00");
                mLlCollection.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //调用收藏接口
                        if (UserManager.toLogin()) {
                            mPresenter.addUserPackageCollection("", mPackageBean.getMembersSdId(), mPackageBean.getMembersSdName(),
                                    mPackageBean.getCombId(), mPackageBean.getCombName());
                        }
                    }
                });
            }
        }
    }

    @Override
    public void deleteCollectionFailed() {

    }

    @Override
    public void firstOrderCheckSuccess(BaseResponse response) {
        if (TextUtils.equals("200", response.getCode())) {
            if (getTipickType()) {
                //如果是需要弹风险提示窗的情况
                if (TextUtils.equals("1", isImmediate)) {
                    pop = new XPopup.Builder(mContext)
                            .isDestroyOnDismiss(false)
                            .isViewMode(true)
                            .autoOpenSoftInput(false)
                            .asCustom(new PackageDetailsPopView(PackageDetailsActivity.this, new PackageDetailsPopView.OnListener() {
                                @Override
                                public void onPositiveClick(PackageDetailsPopView pop, boolean ischeck) {
                                    pop.dismiss();
                                    // 立即下单
                                    ARouter.getInstance()
                                            .build(MallArouterPath.MALL_PLACEORDER)
                                            .withSerializable("package", mPackageBean)
                                            .navigation();
                                }
                            }, "下单须知", tipickContent, "", "", false))
                            .show();
                } else if (TextUtils.equals("0", isImmediate)) {
                    pop = new XPopup.Builder(mContext)
                            .isDestroyOnDismiss(false)
                            .isViewMode(true)
                            .autoOpenSoftInput(false)
                            .asCustom(new PackageDetailsPopView(PackageDetailsActivity.this, new PackageDetailsPopView.OnListener() {
                                @Override
                                public void onPositiveClick(PackageDetailsPopView pop1, boolean ischeck) {
                                    pop.dismiss();
                                    // 议价下单
                                    ARouter.getInstance()
                                            .build(MallArouterPath.MALL_PLACEORDER_BARGAIN)
                                            .withSerializable("package", mPackageBean)
                                            .navigation();

                                }
                            }, "下单须知", tipickContent, "", "", false))
                            .show();
                }
            } else {
                //如果是不需要弹风险提示窗的情况
                // 立即下单
                if (TextUtils.equals("1", isImmediate)) {
                    ARouter.getInstance()
                            .build(MallArouterPath.MALL_PLACEORDER)
                            .withSerializable("package", mPackageBean)
                            .navigation();
                } else if (TextUtils.equals("0", isImmediate)) {
                    // 议价下单
                    ARouter.getInstance()
                            .build(MallArouterPath.MALL_PLACEORDER_BARGAIN)
                            .withSerializable("package", mPackageBean)
                            .navigation();
                }
            }


        } else {
            ToastUtils.showShort(response.getMsg());
        }
    }

    @Override
    public void firstOrderCheckFailed() {
        ToastUtils.showShort("下单校验失败");
    }


    /**
     * 根据价格类型、价差、是否设置电量等多条件，判断下单前风险提示框的内容类型
     * 共四种情况
     * 0不弹框
     * 1有浮动价格或价差，无约定电量，只提示内容1
     * 2无浮动价格和价差，有约定电量，只提示内容2
     * 3有浮动价格或价差，有约定电量，提示内容1+2
     * ①   ②
     */
//    private boolean getTipickType() {
//        boolean shoudShow = true;
////        if (isShowFloPriceTipck) {
////            if (PlaceOrderActivity.getOrderType(mPackageBean) == 3) {
////                //情况1
////                tipickContent = "所选商品价格为浮动价格，各月最终电价将随批发市场实际成交情况波动。";
////            } else {
////                //情况3
////                tipickContent = "①所选商品价格为浮动价格，各月最终电价将随批发市场实际成交情况波动。\n" +
////                        "②请依据实际用电情况申报约定电量，约定电量与实际结算电量的偏差部分（除免偏差范围电量）使用正、负偏差电量对应电价结算。";
////            }
////        } else {
////            if (PlaceOrderActivity.getOrderType(mPackageBean) == 3) {
////                //情况0
////                tipickContent = "";
////                shoudShow = false;
////            } else {
////                //情况2
////                tipickContent = "请依据实际用电情况申报约定电量，约定电量与实际结算电量的偏差部分（除免偏差范围电量）使用正、负偏差电量对应电价结算。";
////            }
////        }
//
//        tipickContent = "①所选商品价格为浮动价格，各月最终电价将随批发市场实际成交情况波动。\n" +
//                "②申报约定电量时，请依据实际用电情况申报约定电量，约定电量与实际结算电量的偏差部分（除免偏差范围电量）使用正、负偏差电量对应电价结算。\n" +
//                "③受电价参数、分时电量占比、偏差电量等不确定因素影响，套餐信息中黄色数值信息与实际存在偏差，请谨慎下单。\n";
//       return shoudShow;
//    }
    private boolean getTipickType() {
        tipickContent = "";
        boolean shoudShow = false;

        /**
         * 提示①：套餐为约定电量时(基准套餐，浮动浮动套餐有一个要约定电量，该套餐就为需要约定电量的套餐），下单须知中需要显示该条提示。
         * 提示②：商品预估价格为橙色的时候，下单须知中需要显示该条提示
         * 提示③：商品预估价格为橙色的时候，下单须知中需要显示该条提示
         * 提示④：商品的标的周期为多月，下单须知中需要显示该条提示
         * 提示⑤：商品预估价格为橙色的时候，下单须知中需要显示该条提示
         */


        if (PlaceOrderActivity.getOrderType(mPackageBean) == 1 || PlaceOrderActivity.getOrderType(mPackageBean) == 2) {
            //套餐为约定电量时  显示1
            tipickContent = "①请依据实际用电情况申报约定电量，约定电量与实际结算电量的偏差部分(除免偏差范围电量) 使用正、负偏差电量对应电价结算。\n";
            if (ispriceOrange) {
                //套餐为约定电量、价格为黄色时  显示1 2 3
                tipickContent = tipickContent + "②如所选商品价格为浮动价格，各月最终电价将随批发市场实际成交情况波动。\n" +
                        "③受电价参数、分时电量占比、偏差电量等不确定因素影响，套餐信息中黄色数值信息与实际存在偏差，请谨慎下单。\n";
                if (isdateDifrent) {
                    //套餐为约定电量、价格为黄色时、标的周期为多月  显示1 2 3 4
                    tipickContent = tipickContent + "④如您下单购买的是多月合约，请仔细查看各月价格。\n";
                    if (ispriceOrange) {
                        //套餐为约定电量、价格为黄色时、标的周期为多月 、价格为黄色时（2）、 显示1 2 3 4 5
                        tipickContent = tipickContent + "⑤预估价未考虑电量偏差，如需测算请进行套餐试算。\n";
                    }
                } else {
                    //套餐为约定电量、价格为黄色时、标的周期非多月 、价格为黄色时（2）、 显示1 2 3 5
                    if (ispriceOrange) {
                        tipickContent = tipickContent + "④预估价未考虑电量偏差，如需测算请进行套餐试算。\n";
                    }
                }
            } else {
                if (isdateDifrent) {
                    //套餐为约定电量 标的周期非多月  显示1 4
                    tipickContent = tipickContent + "②如您下单购买的是多月合约，请仔细查看各月价格。\n";
                    if (ispriceOrange) {
                        //套餐为约定电量 标的周期非多月、 价格为黄色时（2）、 显示1 4 5
                        tipickContent = tipickContent + "③预估价未考虑电量偏差，如需测算请进行套餐试算。\n";
                    }
                } else {
                    if (ispriceOrange) {
                        //套餐为约定电量、价格为黄色时（2）、 显示1  5
                        tipickContent = tipickContent + "②预估价未考虑电量偏差，如需测算请进行套餐试算。\n";
                    }
                }
            }
        } else {
            if (ispriceOrange) {
                //套餐为不约定电量、价格为黄色时、 显示 2 3
                tipickContent = tipickContent + "①如所选商品价格为浮动价格，各月最终电价将随批发市场实际成交情况波动。\n" +
                        "②受电价参数、分时电量占比、偏差电量等不确定因素影响，套餐信息中黄色数值信息与实际存在偏差，请谨慎下单。\n";

                if (isdateDifrent) {
                    //套餐为不约定电量、价格为黄色时、标的周期为多月 、 显示 2 3 4
                    tipickContent = tipickContent + "③如您下单购买的是多月合约，请仔细查看各月价格。\n";
                    if (ispriceOrange) {
                        //套餐为不约定电量、价格为黄色时、标的周期为多月 、价格为黄色时（2）、 显示 2 3 4 5
                        tipickContent = tipickContent + "④预估价未考虑电量偏差，如需测算请进行套餐试算。\n";
                    }
                } else {
                    if (ispriceOrange) {
                        //套餐为不约定电量、价格为黄色时（2）、 显示 2  5
                        tipickContent = tipickContent + "③预估价未考虑电量偏差，如需测算请进行套餐试算。\n";
                    }
                }
            } else {
                if (isdateDifrent) {
                    //套餐为不约定电量、标的周期为单月 、 显示  4
                    tipickContent = tipickContent + "①如您下单购买的是多月合约，请仔细查看各月价格。\n";
                    if (ispriceOrange) {
                        //套餐为不约定电量、标的周期为多月 、价格为黄色时（2）、 显示  4 5
                        tipickContent = tipickContent + "②预估价未考虑电量偏差，如需测算请进行套餐试算。\n";
                    }
                } else {
                    //套餐为不约定电量、价格为黄色时（2）、 显示 5
                    if (ispriceOrange) {
                        tipickContent = "①预估价未考虑电量偏差，如需测算请进行套餐试算。\n";
                    }
                }
            }
        }
        if (TextUtils.isEmpty(tipickContent)) {
            shoudShow = false;
        } else {
            shoudShow = true;
        }
        return shoudShow;
    }


    /**
     * 下单前校验时间区间接口
     *
     * @return
     */
    private boolean checkTimebyBean() {

        boolean canjump = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM");
        try {
            Date startdate = sdf.parse(mPackageBean.getEffectiveDate());
            Date enddate = sdf.parse(mPackageBean.getInvalidDate());

            Date startdateSp = sdf2.parse(mPackageBean.getBuyStartMonth());
            Date enddateSp = sdf2.parse(mPackageBean.getBuyEndMonth());
            Date finalStartDate;
            Date finalEndDate;
            if (startdate.compareTo(startdateSp) > 0) {
                finalStartDate = startdate;
            } else {
                finalStartDate = startdateSp;
            }

            if (enddate.compareTo(enddateSp) < 0) {
                finalEndDate = enddate;
            } else {
                finalEndDate = enddateSp;
            }

            if (finalStartDate != null && finalEndDate != null) {
                Calendar startcalendar = Calendar.getInstance();
                Calendar endcalendar = Calendar.getInstance();
                startcalendar.setTime(finalStartDate);
                endcalendar.setTime(finalEndDate);

                if (TextUtils.equals("04", mPackageBean.getConstrMinCyc())) {
                    mPackageBean.setStartCalender(startcalendar);
                    mPackageBean.setEndCalender(endcalendar);
                    canjump = true;
                } else {
                    int month = endcalendar.get(Calendar.MONTH) - startcalendar.get(Calendar.MONTH) + 1;
                    if (month >= Integer.valueOf(mPackageBean.getConstrMin())) {
                        canjump = true;
                        mPackageBean.setStartCalender(startcalendar);
                        mPackageBean.setEndCalender(endcalendar);
                    } else {
                        ToastUtils.showShort("套餐可购买月份不足，不能下单");
                    }
                }

            } else {
//                ToastUtils.showShort("时间校验有误");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return canjump;

    }

    /**
     * 获取最大可购买月份
     *
     * @return
     */
    private int getMaxMonth() {

        int maxMonth = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSSZ");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM");
        try {
            Date startdate = sdf.parse(mPackageBean.getEffectiveDate());
            Date enddate = sdf.parse(mPackageBean.getInvalidDate());

            Date startdateSp = sdf2.parse(mPackageBean.getBuyStartMonth());
            Date enddateSp = sdf2.parse(mPackageBean.getBuyEndMonth());
            Date finalStartDate;
            Date finalEndDate;
            if (startdate.compareTo(startdateSp) > 0) {
                finalStartDate = startdate;
            } else {
                finalStartDate = startdateSp;
            }

            if (enddate.compareTo(enddateSp) < 0) {
                finalEndDate = enddate;
            } else {
                finalEndDate = enddateSp;
            }

            if (finalStartDate != null && finalEndDate != null) {
                Calendar startcalendar = Calendar.getInstance();
                Calendar endcalendar = Calendar.getInstance();
                startcalendar.setTime(finalStartDate);
                endcalendar.setTime(finalEndDate);
                 maxMonth = endcalendar.get(Calendar.MONTH) - startcalendar.get(Calendar.MONTH) + 1;
            } else {
//                ToastUtils.showShort("最大购买周期计算有误");
            }

        } catch (Exception e) {
            e.printStackTrace();
//            ToastUtils.showShort("最大购买周期计算有误");
        }
        return maxMonth;
    }
}
